package com.pinyoumei.app.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.activity.WebViewActivity;
import com.pinyoumei.app.adapter.PTHistoryAdapter;
import com.pinyoumei.app.adapter.PTHistoryAdapter2;
import com.pinyoumei.app.bean.BaseBean;
import com.pinyoumei.app.bean.HistoryPtBean;
import com.pinyoumei.app.dialog.HistorySubmitDialog;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.view.LoadingDailog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.HashMap;
import java.util.Map;


@SuppressLint("ValidFragment")
public class HistoryPTFragment extends BaseLazyLoadFragment implements View.OnClickListener {
    private String mTitle;
    private Button bt_record_1;
    private Button bt_record_2;
    private LoadingDailog loadingDailog;
    private Gson gson;
    private int type = 1;
    private int page = 1;
    private TextView mTvTotalSpellGroupNum;
    private TextView mTvTotalSpelledNum;
    private TextView mTvTotalNotSpellNum;
    private TextView mTvCanPickNum;
    private TextView mTvPickedNum;
    private RecyclerView rv_1;
    private PTHistoryAdapter2 ptHistoryAdapter2;
    private PTHistoryAdapter ptHistoryAdapter;
    private LinearLayout ll_1;

    public static HistoryPTFragment getInstance(String title) {
        HistoryPTFragment sf = new HistoryPTFragment();
        sf.mTitle = title;
        return sf;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_history;
    }

    @Override
    public void initView(View rootView) {
        LoadingDailog.Builder builder = new LoadingDailog.Builder(getActivity())
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();
        gson = new Gson();

        bt_record_1 = rootView.findViewById(R.id.bt_record_1);
        bt_record_1.setOnClickListener(this);
        bt_record_2 = rootView.findViewById(R.id.bt_record_2);
        bt_record_2.setOnClickListener(this);
        ll_1 = rootView.findViewById(R.id.ll_1);
        LinearLayout ll_kf = rootView.findViewById(R.id.ll_kf);
        ll_kf.setOnClickListener(this);

        SmartRefreshLayout mSwipeRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout);
        mSwipeRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                LoadData();
                refreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                InitData();
                refreshLayout.finishRefresh();
            }
        });


        mTvTotalSpellGroupNum = rootView.findViewById(R.id.tv_total_spell_group_num);
        mTvTotalSpelledNum = rootView.findViewById(R.id.tv_total_spelled_num);
        mTvTotalNotSpellNum = rootView.findViewById(R.id.tv_total_not_spell_num);
        mTvCanPickNum = rootView.findViewById(R.id.tv_can_pick_num);
        mTvPickedNum = rootView.findViewById(R.id.tv_picked_num);


        rv_1 = rootView.findViewById(R.id.rv_1);


    }

    @Override
    public void onFragmentFirst() {
        super.onFragmentFirst();

        InitData();
    }

    private void InitData() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("type", type);
        map.put("page", page);
        map.put("limit", 6);

        OkGo.<String>post(Constants.HISTORY_SPELL_ORDER)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("type", type)
                .params("page", page)
                .params("limit", 6)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        HistoryPtBean historyPtBean = gson.fromJson(response.body(), HistoryPtBean.class);
                        if (historyPtBean.getCode() >= 0) {

                            mTvTotalSpellGroupNum.setText("已团次数 " + historyPtBean.getResult().getTotal_spell_group_num());
                            mTvTotalSpelledNum.setText("已团中次数 " + historyPtBean.getResult().getTotal_spelled_num());
                            mTvTotalNotSpellNum.setText("未团中次数 " + historyPtBean.getResult().getTotal_not_spell_num());

                            mTvCanPickNum.setText(historyPtBean.getResult().getCan_pick_num() + "");
                            mTvPickedNum.setText(historyPtBean.getResult().getPicked_num() + "");


                            switch (type) {
                                case 1:
                                    rv_1.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
                                    ptHistoryAdapter = new PTHistoryAdapter(historyPtBean.getResult().getCan_pick_num(),R.layout.item_pt_order_histroy, historyPtBean.getResult().getOrder_list());
                                    rv_1.setAdapter(ptHistoryAdapter);
                                    View notDataView4 = getLayoutInflater().inflate(R.layout.item_empty_view, (ViewGroup) rv_1.getParent(), false);
                                    ptHistoryAdapter.setEmptyView(notDataView4);

                                    ptHistoryAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                                        @Override
                                        public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                                            switch (view.getId()) {
                                            	case R.id.bt_1:
                                                    PickGoods(ptHistoryAdapter.getData().get(position).getId());
                                            		break;
                                                case R.id.bt_2:
                                                   HistorySubmitDialog historySubmitDialog = new HistorySubmitDialog(getContext(),1,ptHistoryAdapter.getData().get(position).getGoods_price()+"");
                                                   historySubmitDialog.setListener(new HistorySubmitDialog.BtnOnClickListener() {
                                                       @Override
                                                       public void btnonClick(int type) {
                                                           if(type == 1){
                                                               page = 1;
                                                               Convert_funds(ptHistoryAdapter.getData().get(position).getId());
                                                           }
                                                       }
                                                   });
                                                   historySubmitDialog.show();
                                                    break;
                                                case R.id.bt_3:
                                                    HistorySubmitDialog hisSubDialog = new HistorySubmitDialog(getContext(),2,ptHistoryAdapter.getData().get(position).getGoods_price()+"");
                                                    hisSubDialog.setListener(new HistorySubmitDialog.BtnOnClickListener() {
                                                        @Override
                                                        public void btnonClick(int type) {
                                                            if(type == 2){
                                                                page = 1;
                                                                convertScore(ptHistoryAdapter.getData().get(position).getId());
                                                            }
                                                        }
                                                    });
                                                    hisSubDialog.show();
                                                    break;
                                            	default:
                                            		break;
                                            }
                                        }
                                    });

                                    break;
                                case 2:
                                    rv_1.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
                                    ptHistoryAdapter2 = new PTHistoryAdapter2(historyPtBean.getResult().getCan_pick_num(),R.layout.item_pt_order_histroy2, historyPtBean.getResult().getOrder_list());
                                    rv_1.setAdapter(ptHistoryAdapter2);
                                    View notDataView5 = getLayoutInflater().inflate(R.layout.item_empty_view, (ViewGroup) rv_1.getParent(), false);
                                    ptHistoryAdapter2.setEmptyView(notDataView5);
                                    break;

                                default:
                                    break;
                            }
                        } else {
                            Toast.makeText(getActivity(), historyPtBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }



    private void LoadData() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("type", type);
        map.put("page", page);
        map.put("limit", 6);

        OkGo.<String>post(Constants.HISTORY_SPELL_ORDER)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("type", type)
                .params("page", page)
                .params("limit", 6)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        HistoryPtBean historyPtBean = gson.fromJson(response.body(), HistoryPtBean.class);
                        if (historyPtBean.getCode() >= 0) {
                            switch (type) {
                                case 1:

                                    ptHistoryAdapter.addData(historyPtBean.getResult().getOrder_list());
                                    break;
                                case 2:

                                    ptHistoryAdapter.addData(historyPtBean.getResult().getOrder_list());
                                    break;

                                default:
                                    break;
                            }
                        } else {
                            Toast.makeText(getActivity(), historyPtBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }
    private void PickGoods(String order_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("order_id", order_id);


        OkGo.<String>post(Constants.PICKUP_GOODS)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("order_id", order_id)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        BaseBean historyPtBean = gson.fromJson(response.body(), BaseBean.class);
                        if (historyPtBean.getCode() >= 0) {
                            InitData();
                        } else {
                            Toast.makeText(getActivity(), historyPtBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }


    private void Convert_funds(String order_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("order_id", order_id);


        OkGo.<String>post(Constants.CONVERTFUNDS)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("order_id", order_id)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        BaseBean historyPtBean = gson.fromJson(response.body(), BaseBean.class);
                        if (historyPtBean.getCode() >= 0) {
                            InitData();
                        } else {
                            Toast.makeText(getActivity(), historyPtBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_record_1:
                bt_record_1.setTextColor(ContextCompat.getColor(getActivity(), R.color.green_bg));
                bt_record_1.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.shanpe_green_corner_5dp));
                bt_record_2.setTextColor(ContextCompat.getColor(getActivity(), R.color.gary_text_color));
                bt_record_2.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.shanpe_gray_corner_5dp));
                ll_1.setVisibility(View.VISIBLE);
                type = 1;
                page = 1;
                InitData();
                break;

            case R.id.bt_record_2:
                bt_record_1.setTextColor(ContextCompat.getColor(getActivity(), R.color.gary_text_color));
                bt_record_1.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.shanpe_gray_corner_5dp));
                bt_record_2.setTextColor(ContextCompat.getColor(getActivity(), R.color.green_bg));
                bt_record_2.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.shanpe_green_corner_5dp));
                type = 2;
                page = 1;
                InitData();
                ll_1.setVisibility(View.INVISIBLE);
                break;
            case R.id.ll_kf:
                //客服
                if (!TextUtils.isEmpty(Constants.KF_URL)) {
                    final Intent intent2 = new Intent(getActivity(), WebViewActivity.class);
                    intent2.putExtra("order_title", "");
                    intent2.putExtra("url", Constants.KF_URL);
                    startActivity(intent2);
                }
                break;

            default:
                break;
        }
    }

    private void convertScore(String order_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("order_id", order_id);

        OkGo.<String>post(Constants.convertScore)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("order_id", order_id)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        BaseBean historyPtBean = gson.fromJson(response.body(), BaseBean.class);
                        if (historyPtBean.getCode() >= 0) {
                            InitData();
                        } else {
                            Toast.makeText(getActivity(), historyPtBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }
}